﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeGenerator.Dialog
{
    public partial class UpdateConfigDialog : Form
    {
        private ConfigUtil Config { get; } = new ConfigUtil(ConfigUtil.AppConfigFile);
        private JToken AppConfig = null;
        public UpdateConfigDialog()
        {
            InitializeComponent();
        }

        private void UpdateConfigDialog_Load(object sender, EventArgs e)
        {
            var configs = Config.GetConfigs();
            if (configs.Count == 0)
            {
                return;
            }
            AppConfig = configs[0];
            appUpdateUrlInput.Text = AppConfig["appUpdateUrl"].ToString();
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            var shouldAdd = AppConfig == null;
            if (shouldAdd)
            {
                AppConfig = new JObject();
            }
            var url = appUpdateUrlInput.Text;
            if (!Regex.IsMatch(url, @"[a-zA-z]+://[^\\s]*"))
            {
                throw new Exception("请输入合法的URL");
            }
            AppConfig["appUpdateUrl"] = appUpdateUrlInput.Text;
            if (shouldAdd)
            {
                var id = Config.AddConfig(AppConfig);
                AppConfig["id"] = id;
            }
            else
            {
                Config.UpdateConfig(AppConfig);
            }
            Close();
        }
    }
}
